import { RouteLocationNormalized, RouteRecordRaw } from 'vue-router';
import router from '@/router';
import { getToken, setToken } from '@/utils/auth';
import { asyncRoutes } from '@/router';
import { useUserStore } from '@/store';

import NProgress from 'nprogress'; // 进度条
import 'nprogress/nprogress.css'; // 进度条样式

//权限判断方法
import { hasPermission, hasRouter } from '@/utils/permission';

//配置进度条
NProgress.inc(0.2);
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false });

//路由白名单
const whiteList = ['/login', '/401', '404'];
setToken('/'); //开发写入token 通过校验

router.beforeEach(async (to: RouteLocationNormalized, form: RouteLocationNormalized, next: any) => {
    //开启进度条
    NProgress.start();

    const userStore = useUserStore(); //获取pinia实例

    //如果跳转页面为白名单 直接放行
    if (whiteList.indexOf(to.path) !== -1) {
        next();
        NProgress.done(); //关闭加载进度条
        return;
    }

    //未登录状态
    if (!getToken()) {//判断未登录 直接跳转登陆页面
        next('/login');
        NProgress.done(); //关闭加载进度条
        return;
    }

    //判断是否已经动态注入路由 
    const routesList = userStore.routesList;

    if (routesList.length) {//已注入路由 

        //当前访问页面为登陆 跳转拥有权限的第一个页面
        if (to.path == '/login') {
            next({ path: routesList[0].path, replace: true });
            NProgress.done(); //关闭加载进度条
            return;
        }
        //判断是否有权限进入
        if (hasPermission(to, router.getRoutes())) {
            next();
        } else if (hasRouter(to, asyncRoutes)) {
            next({ path: '/401' });
        } else {
            next();
        }

        NProgress.done(); //关闭加载进度条
        return;
    }

    //根据权限 动态增加路由
    const routes = await userStore.getUserPermissions();
    
    routes.forEach((route: RouteRecordRaw) => {
        router.addRoute(route);
    });
    next({ ...to, replace: true });
    NProgress.done(); //关闭加载进度条
});

router.afterEach(() => {
    NProgress.done(); //关闭加载进度条
});